package com.icloud.cer.rest.common;

import java.text.MessageFormat;
import java.util.Locale;

import com.icloud.cer.rest.i18n.ErrorCodeHolder;
import com.icloud.cer.rest.util.ArrayUtils;
import com.icloud.cer.rest.util.StringUtils;

public class BizException extends RuntimeException {
	private static final long serialVersionUID = 1088127938583130518L;
	protected String messageCode;
	protected String populatedMessage;
	private Object[] formatObjects = null;
	
	protected BizException(){
		
	}
	
	protected BizException(String messageCode) {
		super();
		this.messageCode = messageCode;
	}
	
	protected BizException(Throwable cause){
		super(cause);
	}
	
	protected BizException(String messageCode, Throwable cause) {
		super(cause);
		this.messageCode = messageCode;
	}
	
	public BizException(String messageCode, Throwable cause, Object... objects) {
		super(messageCode, cause);
		this.messageCode = messageCode;
		if(cause!=null){
			String errorMsg =StringUtils.exceptionSummary(cause);
			this.formatObjects = ArrayUtils.add(objects, errorMsg);
		}else{
			this.formatObjects=objects;
		}
		if(this.formatObjects!=null){
			for(int i=0;i<formatObjects.length;i++){
				if(formatObjects[i]==null){
					formatObjects[i] = "";
				}
			}
		}
	}
	
	public BizException(String messageCode, Object ...objects ){
		this(messageCode,null,objects);
	}
	
	public BizException(long messageCode,Object ...objects ){
		this(String.valueOf(messageCode),null,objects);
	}
	
	public BizException(long messageCode, Throwable cause, Object ...objects){
		this(String.valueOf(messageCode), cause,objects);
	}
	
	//获取错误代码
	public String getCode(){
		return messageCode;
	}
	
	@Override
	public String getMessage(){
		return getFormattedMessage();
	}
	public String getFormattedMessage(){
		return getFormattedMessage(null);
	}
	
	public void clear() {
		this.formatObjects = null;
	}
	
	public String toString() {
        return getClass().getName()+getMessage();
    }
	
	@Override
	public String getLocalizedMessage() {
		String code= getCode();
        String message = getFormattedMessage();
        StringBuilder sb = new StringBuilder();
        sb.append(":[").append(code).append("]");
        if(StringUtils.isNotEmpty(message)){
        	sb.append(message);
        }
        return sb.toString();
	}
	
	public String getFormattedMessage(Locale locale) {
		if(populatedMessage!=null){
			return populatedMessage;
		}
		if(locale==null){
			locale=Locale.getDefault();
		}
		String code=getCode();
		if(code==null){
			return this.getClass().getName()+" "+getStackTrace()[0].toString();
		}
		
		String template = ErrorCodeHolder.getInstance().get(code,locale);
		if (template == null){
			return code;
		}
		if (formatObjects == null || formatObjects.length == 0) {
			return template;
		} else {
			return MessageFormat.format(template, formatObjects);
		}
	}
}
